package servletContext;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * ServletContext功能：
 *  1.获取MIME类型
 * - MIME类型：在互联网通信过程中定义的一种文件数据类型
 *   - 格式：大类型/小类型    text/html    image/jpeg
 * - 获取：String getMimeType(String file)
 * 2.域对象
 * 3.获取文件的服务器路径
 * 方法：String  getRealPath(String path)
 *    获取到该资源目录下a.txt  b.txt  c.txt的路径信息
 *
 * @author Mc.Chai
 * @program: JavaWeb
 * @create 2022-03-23-15:34 15:34
 */
@WebServlet("/servletContextDemo2")
public class ServletContextDemo2 extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ServletContext servletContext = request.getServletContext();
        /**获取MIME类型*/
        String file="a.jpg";
        String mimeType = servletContext.getMimeType(file);
        System.out.println(mimeType);
        /**域对象：共享数据*/
        servletContext.setAttribute("msg","chai");
        /**获取文件的服务器路径*/
        //注：WEB-INF需要大写，注意src下文件的访问方式
        //获取web下的资源路径
        String realPath1 = servletContext.getRealPath("/a.txt");
        //获取WEB-INF下的资源路径
        String realPath2 = servletContext.getRealPath("/WEB-INF/b.txt");
        //获取src下的资源路径
        String realPath3 = servletContext.getRealPath("/WEB-INF/classes/c.txt");
        System.out.println(realPath1);
        System.out.println(realPath2);
        System.out.println(realPath3);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }
}
